<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>组拖动和编辑</title>
  <script src="./konva.min.7-2-5.js"></script>
  <style>
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
    }

    #container {
      background-color: #f0f0f0;
    }
  </style>
</head>

<body>
  <div id="container"></div>

  <script>
    // 创建舞台
    const stage = new Konva.Stage({
      container: 'container',
      width: window.innerWidth,
      height: window.innerHeight,
    })

    // 创建图层
    const layer = new Konva.Layer()
    stage.add(layer)

    // 创建一个可拖动的组
    const group = new Konva.Group({
      draggable: true,
      x: 500,
      y: 200,
    })

    // 创建矩形
    const rect = new Konva.Rect({
      x: 0,
      y: 0,
      width: 200,
      height: 200,
      fill: '#00D2FF',
      stroke: 'black',
      strokeWidth: 2,
    })

    // 创建文本标签
    const text = new Konva.Text({
      x: 50,
      y: 50,
      text: 'Click to edit',
      fontSize: 18,
      fontFamily: 'Arial',
      fill: 'black',
    })

    // 添加矩形和文本到组
    group.add(rect)
    group.add(text)
    layer.add(group)

    // 添加拖动事件
    group.on('dragmove', () => {
      console.log('Group is being dragged')
    })
    group.on('click', () => {
      transformer.nodes([text])
      transformer.getLayer().batchDraw()
    })

    // 使用 transformer 编辑文本
    const transformer = new Konva.Transformer({
      nodes: [],
      // 可选：设定 transformer 的外观
      borderStroke: 'red',
      borderStrokeWidth: 2,
      anchorSize: 10,
      resizeEnabled: true,
      rotateEnabled: false,
      preserveAspectRatio: true,
    })
    layer.add(transformer)


    // 点击舞台其他地方以隐藏 transformer
    stage.on('click', (e) => {
      if (e.target === stage) {
        transformer.nodes([]) // 隐藏 transformer
        transformer.getLayer().batchDraw()
      }
    })

    // 添加 layer 并渲染
    layer.draw();
  </script>
</body>

</html>